<template>
  <div class="bg">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>登录</span>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="50px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSubmit(formRef)" type="primary">登录</el-button>
        </el-form-item>
      </el-form>
      <el-row justify="space-between">
        <el-col :span="5">
          <el-link href="/#/register" type="info">注册账号</el-link>
        </el-col>
        <el-col :span="5">
          <el-link type="info">忘记密码?</el-link>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
  
<script setup>
import { ref, reactive } from 'vue'
import Admin from '@/api/admin';
import { useRouter, useRoute } from 'vue-router';
let form = reactive({
  username: '',
  password: '',
});
//获取form组件实例
let formRef = ref();
//表单验证规则
const rules = reactive({
  username: [
    // 为空执行上行，输入执行下行
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账户长度3到20', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /\d{3,}/, message: '账户长度3到20', trigger: 'blur' },
  ],
});
//获取router实例对象
let router = useRouter();
let route = useRoute();
//登录
function handleSubmit(formEl) {
  //校验整个表单
  formEl.validate(async (valid, fields) => {
    if (valid) {
      // Admin.login({...form}).then((res)=>{
      //   console.log(res);
      // });
      //解构res
      let { status, msg, data } = await Admin.login({ ...form });
      if (status) {
        // 缓存数据
        sessionStorage.id = data.id;
        sessionStorage.role = data.role;
        sessionStorage.token = data.token;
        // 登陆成功
        ElMessage.success(msg);
        let { redirect } = route.query;
        console.log(redirect);
        if (redirect) {
          router.replace(redirect);
        } else {
          //跳转页面
          router.push('/aritcle/list')
        }
      } else {
        // 登陆失败
        ElMessage.error(msg);
        // alert(msg);
      }
    } else {
      //没通过校验
      console.log('校验失败字段', fields);
    }

  })
}

</script>
<style lang="less" scoped>
.bg {
  position: relative;
  min-height: 100vh;
  background: url(../assets/img/login/bg.jpg) top center;
  background-size: cover;

  .form-card {
    width: 400px;
    position: absolute;
    top: 50%;
    right: 30px;
    transform: translateY(-50%);
  }
}
</style>